<template>
  <div>
    <!-- 路径 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <div style="margin-top: 15px">
        <el-row :gutter="20">
          <!-- 搜索栏 -->
          <el-col :span="7">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="queryUsers"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="queryUsers"
              ></el-button>
            </el-input>
          </el-col>
          <!-- 添加用户 -->
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>
      <!-- 用户列表详细数据 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" width="50px"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUSer(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="1"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="closeAddDialog"
    >
      <!-- 主体部分 -->
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户数据对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="closeEditDialog"
    >
      <!-- 主体部分 -->
      <el-form
        ref="editUSerRef"
        :model="editUser"
        :rules="editUserRules"
        label-width="100px"
      >
        <el-form-item label="姓名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="assignDialogVisible"
      width="50%"
      @closed="closeAssignDialog"
    >
      <!-- 主体部分 -->
      <div>
        <p>姓名：{{assignRolesForm.username}}</p>
        <p>角色：{{assignRolesForm.role_name}}</p>
        <p>选择新角色：
          <template>
            <el-select v-model="selectedRoleId" placeholder="请选择" clearable>
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRolesInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  created() {
    // 请求用户数据
    this.queryUsers()
    // 请求角色列表
    this.queryRolesList()
  },
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱！'))
    }
    // 验证手机的规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机！'))
    }
    return {
      // 请求参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      // 存储用户数据
      userList: [],
      // 返回总条目数
      total: 0,
      // 搜索词条
      searchKeyWord: '',
      // 控制添加用户页面的显示
      addDialogVisible: false,
      // 添加用户数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加用户校验规则
      addUserRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在3到5个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制修改用户页面的显示
      editDialogVisible: false,
      // 修改用户的数据
      editUser: {},
      // 修改用户校验规则
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制分配角色对话框的显示
      assignDialogVisible:false,
      // 分配角色数据
      assignRolesForm:{},
      // 角色列表
      rolesList:[],
      // 选项角色Id
      selectedRoleId:''
    }
  },
  methods: {
    // 请求用户数据
    async queryUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败!')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 更改页面显示数目
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.queryUsers()
    },
    // 更改页码
    handleCurrentChange(newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.queryUsers()
    },
    // 更改用户状态
    async changeUserState(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改状态失败！')
      }
      this.$message.success('修改状态成功！')
    },
    // 关闭添加用户对话框
    closeAddDialog() {
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserRef.validate(async (value) => {
        if (!value) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meata !== 201) this.$message.error('添加用户失败！')
        this.$message.success('添加用户成功！')
        this.addDialogVisible = false
        this.queryUsers()
      })
    },
    // 修改用户数据
    async editUSer(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200)
        return this.$message.error('请求用户数据失败')
      this.editUser = res.data
      this.editDialogVisible = true
    },
    // 关闭修改用户对话框
    closeEditDialog() {
      this.$refs.editUSerRef.resetFields()
    },
    // 提交修改用户数据
    editUserInfo() {
      this.$refs.editUSerRef.validate(async (value) => {
        if (!value) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUser.id,
          {
            email: this.editUser.email,
            mobile: this.editUser.mobile,
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改用户数据失败')
        this.$message.success('修改用户数据成功！')
        this.editDialogVisible = false
        this.queryUsers()
      })
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const {data:res} = await this.$http.delete('users/'+id)
          if(res.meta.status!==200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.queryUsers()
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    // 获取角色列表
    async queryRolesList(){
      const{data:res}=await this.$http.get('roles')
      if(res.meta.status!==200) return this.$message.error('获取角色列表失败')
      this.rolesList=res.data
    },
    // 分配角色
    assignRoles(assignRolesForm){
      this.assignRolesForm = assignRolesForm
      this.assignDialogVisible=true
    },
    // 关闭分配角色对话框
    closeAssignDialog(){
      this.selectedRoleId=''
    },
    // 提交用户角色的分配
    async assignRolesInfo(){
      if(!this.selectedRoleId) return this.$message.error('请选择角色！')
      const {data:res}=await this.$http.put(`users/${this.assignRolesForm.id}/role`,{rid:this.selectedRoleId})
      if(res.meta.status!==200) return this.$message.error('修改用户角色失败！')
      this.$message.success('修改用户角色成功！')
      this.assignDialogVisible=false
      this.queryUsers()
    }
  },
}
</script>

<style lang="less" scoped>
</style>>